import { fileSave, renameFile } from '@/api/modules/tool/file/file';
import { openNotepad } from '@/global/window/widget';
import { getData } from '@/global/window/window';
import { response } from '@/utils/table/table';
import { concatWithSeparator } from './action';
import { currentFolder, currentPath, editingFile, selectedFile } from './data';

export const renameForFile = async (sourceName: string, targetName: string) => {
  const newName = concatWithSeparator(currentPath.value, sourceName);
  const oldName = concatWithSeparator(currentPath.value, targetName);
  await renameFile(newName, oldName);
};
export const editFileName = () => {
  if (selectedFile.value) {
    editingFile.value = selectedFile.value.title;
    selectedFile.value.edit = true;
  }
};

const create = (type: 'folder' | 'file', title: string) => {
  let obj = {
    children: [],
    key: currentPath.value,
    title,
    type,
    edit: true,
    isNew: true,
  };
  editingFile.value = title;
  if (currentFolder.value) {
    currentFolder.value.push(obj);
    selectedFile.value = obj;
  }
};
export const createFolder = () => {
  create('folder', '新建文件夹');
};
export const createFile = () => {
  create('file', '新建文件');
};
/* 用记事本打开文件 */
export const openWithNotepad = (data: string) => {
  const id = `${selectedFile.value?.key!}`;
  openNotepad({
    data,
    id,
    /* 点击记事本保存的逻辑 */
    async save(callbackData: any) {
      await response(fileSave, id, callbackData.data);
    },
  });
};
